package coop.bancocredicoop.proyectos.gd.jobs

import grails.gsp.PageRenderer

import org.apache.commons.logging.LogFactory
import org.quartz.Job
import org.quartz.JobExecutionContext

import coop.bancocredicoop.proyectos.gd.Document
import coop.bancocredicoop.proyectos.gd.DocumentType
import coop.bancocredicoop.proyectos.gd.DocumentsCSVWriter

class ResumidorDiarioDeExcepciones implements Job {

    private static final log = LogFactory.getLog(this)
    def documentService
    def mailService
    PageRenderer groovyPageRenderer

    def void execute(JobExecutionContext context) {
        def dataMap = context.getMergedJobDataMap()
        Date today = getToday()
        def tomorrow = today.plus(1) 
        def documentType = DocumentType.findByShortName('Excepcion')
        def documents = documentService.getDocumentsByTypesAndDate([documentType], today, tomorrow)
        if (documents.size() == 0) {
            log.info("No se encontraron documentos del tipo " +
                 "${documentType.toString()} cargados el día " + 
                 "${today.format('yyyy-MM-dd')}")
        } else {
            log.info("${documents.size()} documentos encontrados del tipo " + 
                "${documentType.toString()} cargados el día " + 
                "${today.format('yyyy-MM-dd')}. " + 
                "Enviando correo a '${documentType.uploadNotificationEmailAddress}' ...")
            def csvContent = getCSV(documents)
            sendMail(documentType.uploadNotificationEmailAddress, 
                     getDocumentModel(documents),
                     csvContent,
                     today)                     
        } 
    }

    def private getToday() {
        Calendar c = new GregorianCalendar()
        c.set(Calendar.HOUR_OF_DAY, 0)
        c.set(Calendar.MINUTE, 0)
        c.set(Calendar.SECOND, 0)
        c.getTime()        
    }

    def private getDocumentModel(documents) {
        def documentModel = []
        Document.withTransaction {
            documents.each {  
                def document = Document.get(it.id)
                documentModel.add([
                idCliente: document.customer.idPersona,
                cuit: document.customer.cuit,
                customerName: document.customer.name,
                documentName: document.name
                ])
            }
        }
        documentModel
    }

    def getCSV(documents) {
        def outputStream = new ByteArrayOutputStream()
        def csvWriter = new DocumentsCSVWriter(outputStream)
        Document.withTransaction { 
            def attachedDocuments = documents.collect { Document.get(it.id) } 
            csvWriter.write(attachedDocuments)    
        }
        def csvContent = outputStream.toString()
        outputStream.close()
        csvContent
    }

    def sendMail(emailAddress, documents, csvContent, day) {

        def summarySubject = ("Resumen diario de excepciones - " + 
                              "${day.format('yyyy-MM-dd')}")
        def model = [documents: documents, day: day]
        def mailBody = groovyPageRenderer.render(view: '/email/resumenDiarioExcepciones', model: model)
        try {
            mailService.sendMail { 
                multipart true
                to emailAddress
                subject summarySubject
                html mailBody 
                attachBytes "Excepciones-${day.format('yyyy-MM-dd')}.csv", "text/csv", csvContent.getBytes("UTF-8")
           }
        } catch (Exception e) { 
            log.fatal("Error enviando email", e)
        }


    }

}

